package 牛客剑指专题二刷.链表;

/**
 * author:JiangSong
 * Date:2023/7/3
 **/

import java.util.*;

/**
 * 反向遍历链表
 法1：普通遍历,add(0,val)
 法2：栈
 法3：递归
 */

public class JZ6 {
    class ListNode{
        int val;
        ListNode next = null;
        ListNode(int val){
            this.val = val;
        }
    }
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        Stack<Integer> stack = new Stack<>();
        ArrayList<Integer> res = new ArrayList<>();
        ListNode t = listNode;
        while(t != null){
            stack.push(t.val);
            t = t.next;
        }
        while (!stack.isEmpty()){
            res.add(stack.pop());
        }
        return res;
    }

    private ArrayList<Integer> result = new ArrayList<>();
    public ArrayList<Integer> printListFromTailToHead2(ListNode listNode) {
        if(listNode == null){
            return result;
        }
        printListFromTailToHead2(listNode.next);
        result.add(listNode.val);
        return result;
    }
}
